package com.lantian.yjmall.product.service.impl;

import com.lantian.yjmall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantian.common.utils.PageUtils;
import com.lantian.common.utils.Query;

import com.lantian.yjmall.product.dao.CategoryDao;
import com.lantian.yjmall.product.entity.CategoryEntity;
import com.lantian.yjmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 根据sort排序获取所有分类列表集合
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        List<CategoryEntity> entities = baseMapper.selectList(wrapper);

        // 组装成父子的树形结构
        //     找到所有的一级分类设置children
        List<CategoryEntity> oneMenu = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0)
                .map((menu)-> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .collect(Collectors.toList());

        return oneMenu;
    }

    /**
     * 根据id 删除分类
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 1,检查当前删除的菜单，是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 根据当前分类id  封装完整三级分类id[]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        //  逆序集合
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());


    }

    // 收集三级分类完整id  例[255,25,2]
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        // 收集当前分类categoryID
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }


    /**
     * 递归查找所有菜单的子菜单
     * @param menu
     * @param entities
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity menu, List<CategoryEntity> entities) {
        List<CategoryEntity> children = entities.stream()
                // long 类型超过-128~127 不能用== 判断
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(menu.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, entities));
                    return categoryEntity;
                })
                .collect(Collectors.toList());

        return children;
    }


}
